package com.seeyon.apps.seepkk.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.seeyon.apps.collaboration.api.CollaborationApi;
import com.seeyon.apps.collaboration.event.CollaborationFinishEvent;
import com.seeyon.apps.collaboration.event.CollaborationStartEvent;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.listener.BaseListener;
import com.seeyon.apps.kk.manager.FormDataBaseManager;
import com.seeyon.apps.kk.util.JdbcAgentUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.content.comment.CommentManager;
import com.seeyon.ctp.common.permission.manager.PermissionManager;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.annotation.ListenEvent;
import com.seeyon.ctp.workflow.wapi.WorkflowApiManager;
import com.seeyon.v3x.worktimeset.manager.WorkTimeManager;

/**
 * PT活动申请 流程监听类
 *
 * @author yuyz@seeyon.com
 */
public class SeepKkApplicationForActivitiesListener extends BaseListener {

    private static final Log log = LogFactory.getLog(SeepKkApplicationForActivitiesListener.class);

    public OrgManager getOrgManager() {
        return orgManager;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public WorkflowApiManager getWapi() {
        return wapi;
    }

    public void setWapi(WorkflowApiManager wapi) {
        this.wapi = wapi;
    }

    public FormApi4Cap4 getFormApi4Cap4() {
        return formApi4Cap4;
    }

    public void setFormApi4Cap4(FormApi4Cap4 formApi4Cap4) {
        this.formApi4Cap4 = formApi4Cap4;
    }

    public AffairManager getAffairManager() {
        return affairManager;
    }

    public void setAffairManager(AffairManager affairManager) {
        this.affairManager = affairManager;
    }

    public WorkTimeManager getWorkTimeManager() {
        return workTimeManager;
    }

    public void setWorkTimeManager(WorkTimeManager workTimeManager) {
        this.workTimeManager = workTimeManager;
    }

    public CommentManager getCtpCommentManager() {
        return ctpCommentManager;
    }

    public void setCtpCommentManager(CommentManager ctpCommentManager) {
        this.ctpCommentManager = ctpCommentManager;
    }

    public CollaborationApi getCollaborationApi() {
        return collaborationApi;
    }

    public void setCollaborationApi(CollaborationApi collaborationApi) {
        this.collaborationApi = collaborationApi;
    }

    public PermissionManager getPermissionManager() {
        return permissionManager;
    }

    public void setPermissionManager(PermissionManager permissionManager) {
        this.permissionManager = permissionManager;
    }

    private OrgManager orgManager;
    private WorkflowApiManager wapi;
    private FormApi4Cap4 formApi4Cap4;
    private AffairManager affairManager;
    private WorkTimeManager workTimeManager;
    private CommentManager ctpCommentManager;
    private CollaborationApi collaborationApi;
    private PermissionManager permissionManager;
    private FormDataBaseManager kkBaseFormManager;

    public void setKkBaseFormManager(FormDataBaseManager kkBaseFormManager) {
        this.kkBaseFormManager = kkBaseFormManager;
    }

    // 发起
    @ListenEvent(event = CollaborationStartEvent.class, async = true)
    public void onCollaborationStartEvent(CollaborationStartEvent event) {
        try {
            ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
            FormBean formBean = formApi4Cap4.getForm(summary.getFormAppid());
            FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
                    formBean, null);
            CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
            Map<String, Object> formdata = formMasterBean.getAllDataMap();
            String[] templetSubject = Constants.seepPTCode.split(",");
            Thread newThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10 * 1000);
                        log.info("#强生客开，发起后事件！");
                        if (ArrayUtils.contains(templetSubject, template.getTempleteNumber())) {
                            // 获取会议日程重复表信息
                            List<FormTableBean> tableList = formBean.getTableList();
                            for (FormTableBean formTableBean : tableList) {
                                if (formTableBean.getDisplay().equals("会议日程")) {
                                    Map<String, Object> params = Maps.newHashMap();
                                    params.put("formmainId", summary.getFormRecordid());
                                    reSort(formTableBean, params);
                                }
                            }

                            int flag = StringUtils.indexOf(template.getTempleteNumber(), "_"); // 标记是否是活动申请外的其他表单
                            /**
                             * 设置通用 按照示例 配置模板编号 示例 表名 模板编号 PT活动申请 formCode007 PT活动报备
                             * formCode007_1 PT活动回填 formCode007_2 PT活动申请底表 formCode007_3
                             */
                            String filedName = -1 == flag ? formBean.getFieldBeanByDisplay("活动编号").getName()
                                    : formBean.getFieldBeanByDisplay("请选择活动编号").getName();

                            // 下拉多选数据 key=控件名称
                            Map<String, Object> selectionMap = Maps.newHashMap();
                            for (FormFieldBean fieldBean : formBean.getAllFieldBeans()) {
                                if ("5550438035101852361".equals(fieldBean.getInputType())) {
                                    if (null != MapUtils.getObject(formdata, fieldBean.getName())
                                            && !"".equals(MapUtils.getObject(formdata, fieldBean.getName()))) {
                                        selectionMap.put(fieldBean.getDisplay(), MapUtils.getObject(formdata, fieldBean.getName()));
                                    }
                                }
                            }
                            // 写入底表
                            String bottomTableCode = template.getTempleteNumber() + "_3"; // 活动申请底表
                            if (-1 != flag) {
                                bottomTableCode = template.getTempleteNumber().substring(0, flag) + "_3";
                            }
                            log.info("#强生客开，下拉多选数据写入底表模板编号：" + bottomTableCode);
                            seavPTBottomTable(selectionMap, MapUtils.getString(formdata, filedName), bottomTableCode);
                        }
                    } catch (Exception e) {
                       log.error("#强生客开，下拉多选数据写入错误：",e);
                    }
                }
            });
            newThread.start();
        } catch (Exception e) {
            log.error("##强生客开异常", e);
        }
    }

    // 结束
    public void CollaborationFinishEvent(CollaborationFinishEvent event) {
        try {
            log.info("========================stopEvent===========================");
            ColSummary summary = collaborationApi.getColSummary(event.getSummaryId());
            FormBean formBean = formApi4Cap4.getForm(summary.getFormAppid());
            CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
            FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
                    formBean, null);
            Map<String, Object> formdata = formMasterBean.getAllDataMap();
            String[] templetSubject = Constants.seepPTCode.split(",");
            if (ArrayUtils.contains(templetSubject, template.getTempleteNumber())) {
                int flag = StringUtils.indexOf(template.getTempleteNumber(), "_"); // 标记是否是活动申请外的其他表单
                /**
                 * 设置通用 按照示例 配置模板编号 示例 表名 模板编号 PT活动申请 formCode007 PT活动报备
                 * formCode007_1 PT活动回填 formCode007_2 PT活动申请底表 formCode007_3
                 */
                String filedName = -1 == flag ? formBean.getFieldBeanByDisplay("活动编号").getName()
                        : formBean.getFieldBeanByDisplay("请选择活动编号").getName();

                // 下拉多选数据 key=控件名称
                Map<String, Object> selectionMap = Maps.newHashMap();
                for (FormFieldBean fieldBean : formBean.getAllFieldBeans()) {
                    if ("5550438035101852361".equals(fieldBean.getInputType())) {
                        if (null != MapUtils.getObject(formdata, fieldBean.getName())
                                && !"".equals(MapUtils.getObject(formdata, fieldBean.getName()))) {
                            selectionMap.put(fieldBean.getDisplay(), MapUtils.getObject(formdata, fieldBean.getName()));
                        }
                    }
                }
                // 写入底表
                String bottomTableCode = template.getTempleteNumber() + "_3"; // 活动申请底表
                if (-1 != flag) {
                    bottomTableCode = template.getTempleteNumber().substring(0, flag) + "_3";
                }
                log.info("#强生客开，下拉多选数据写入底表模板编号：" + bottomTableCode);
                seavPTBottomTable(selectionMap, MapUtils.getString(formdata, filedName), bottomTableCode);
            }
        } catch (Exception e) {
            log.error("##强生客开异常", e);
        }
    }

    /**
     * PT活动申请 下拉多选控件值 流程结束后写入底表
     *
     * @param param
     * @param ptNo
     * @param formCode
     * @throws Exception
     */
    public void seavPTBottomTable(Map<String, Object> param, String ptNo, String formCode) throws Exception {
        if (null == ptNo || "".equals(ptNo) || param.isEmpty()) {
            log.info("#强生客开,下拉多选数据写入失败，活动编号:" + ptNo);
            return;
        }
        FormBean bean = formApi4Cap4.getFormByFormCode(formCode);
        StringBuilder sb = new StringBuilder("update ");
        log.info("#强生客开，下拉多选数据写入,start");
        FormTableBean formTableBean = bean.getMasterTableBean();
        sb.append(formTableBean.getTableName() + " set ");
        List list = new ArrayList();
        param.forEach((k, v) -> {
            if (null != v) {
                sb.append(bean.getFieldBeanByDisplay(k).getName() + "=?,");
                list.add(v);
            }
        });
        sb.deleteCharAt(sb.length() - 1); // 去除最后一个参数的 逗号
        list.add(ptNo);
        sb.append(" where " + bean.getFieldBeanByDisplay("活动编号").getName() + "=?");
        log.info("#强生客开，下拉多选数据写入,SQL 生成 ：" + sb.toString());
        JdbcAgentUtil.doUpdateOrInsert(sb.toString(), list);
        log.info("#强生客开，下拉多选数据写入：" + sb.toString());
    }

    /**
     * 按会议开始时间重新排序
     *
     * @param formTableBean
     * @param params
     */
    public void reSort(FormTableBean formTableBean, Map<String, Object> params) throws Exception {
        StringBuilder selectSql = new StringBuilder();
        String tableName = formTableBean.getTableName();
        selectSql.append("select " + tableName + ".id from " + tableName);
        selectSql.append(" LEFT JOIN CTP_ENUM_ITEM ON CTP_ENUM_ITEM.ID = "
                + formTableBean.getFieldBeanByDisplay("会议会场").getName());
        selectSql.append(" where formmain_id =:formmainId  ORDER BY CTP_ENUM_ITEM.SHOWVALUE,"
                + formTableBean.getFieldBeanByDisplay("会议开始时间").getName());
        log.info("#强生会议日程排序SQL:" + selectSql.toString());
        List<Map> datList = JdbcAgentUtil.doQuery(selectSql.toString(), params);
        if (!datList.isEmpty() && datList.size() > 1) {
            int sort = 0;
            for (Map map : datList) {
                List param = Lists.newArrayList();
                sort++;
                param.add(sort);
                param.add(MapUtils.getString(map, "id"));
                updateSort(param, tableName);
            }
        }
    }

    /**
     * 更新排序
     *
     * @param params
     * @throws Exception
     */
    public void updateSort(List params, String tableName) throws Exception {
        if (params.isEmpty()) {
            log.info("#强生客开，PT活动申请，会议日程按开始时间重新排序错误:" + params);
            return;
        }
        StringBuilder updateSql = new StringBuilder();
        updateSql.append("update " + tableName + " set sort =? where id =?");
        JdbcAgentUtil.doUpdateOrInsert(updateSql.toString(), params);
        log.info("#强生客开，PT活动申请，会议日程按开始时间重新排序：" + updateSql.toString());
    }
}
